package com.hutao.sso.controller;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hutao.sso.pojo.TCzy;
import com.hutao.sso.pojo.authority.Authority;
import com.hutao.sso.pojo.user.Users;
import com.hutao.sso.service.UserService;
import com.hutao.sso.service.authority.AuthorityService;
import com.hutao.sso.service.medicalMainstay.MedicalMainstayPathService;
import com.hutao.sso.service.user.UsersService;
import com.hutao.sso.util.Constant;
import com.hutao.sso.util.CookieUtils;
import com.hutao.sso.util.Encrypt;
import com.hutao.sso.util.ExceptionUtil;
import com.hutao.sso.util.MD5;
import com.hutao.sso.util.ResponseUtil;
import com.hutao.sso.util.Result;

@RequestMapping("/user")
@Controller
public class UserLoginController {
	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserService userService;

	
	@Autowired
	private MedicalMainstayPathService medicalMainstayPathService;
	
	@Autowired
	private UsersService usersService;
	
	@Autowired
	private AuthorityService authorityService;
	
	@GetMapping("/authority/index")
	public String index(String  contextPath, Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
		System.out.println(contextPath);
		Map<String, Object> medicalMainstayPathMap = medicalMainstayPathService.findMedicalMainstayByContextPath(contextPath);
		map.put("medicalMainstayId", medicalMainstayPathMap.get("medical_mainstay_id"));
		return "/login";
	}
	
	@GetMapping("/loginOut")
	public String loginOut(Map<String, Object> map, HttpSession session) {
		Users user = (Users) session.getAttribute("current_user");
		String medicalMainstayId = "";
		
		if (user != null) {
			medicalMainstayId = user.getMedicalMainstayId();
		}
		
		map.put("medicalMainstayId", medicalMainstayId);
		return "/login";
	}
	
	/**
	 * 跳到权限登录页
	 * 
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 */
	@PostMapping("/authority/login")
	@ResponseBody
	public Result authorityLogin(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
		
		Map<String, Object> params = new HashMap<>();
		params.put("loginName", request.getParameter("loginName"));
		params.put("password", MD5.md5(request.getParameter("password")));
		params.put("medicalMainstayId", request.getParameter("medicalMainstayId"));
		Map<String, Object> userMap = usersService.findUserHospitalByLoginNameAndPassword(params);
		//从契约里面登录
		if(null != userMap) {
			Users user = new Users();
			user.setLoginName(userMap.get("login_name")!=null?(String)userMap.get("login_name"):"");
			user.setPassword(userMap.get("password")!=null?(String)userMap.get("password"):""); 
			user.setMedicalMainstayId(userMap.get("medical_mainstay_id")!=null?(String)userMap.get("medical_mainstay_id"):null);
			user.setId(userMap.get("id")!=null?(String)userMap.get("medical_mainstay_id"):null);
			user.setIsRealUser(1);
			user.setName(userMap.get("name")!=null?(String)userMap.get("name"):"");
			session.setMaxInactiveInterval(-1);
			
			session.setAttribute("current_user", user);
			return new Result(true, "登录成功!");
		}else {
			//从用户里面登录
			Users user = usersService.findUserByLoginNameAndPassword(params);
			if(null != user) {
				user.setIsRealUser(2);
				session.setAttribute("current_user", user);
				return new Result(true, "登录成功!");
			}
		}
		return new Result(false, "登录失败!");
	}
	
	/**
	 * 客户端证书登录
	 * 
	 */
	@PostMapping("/clientCertificateLogin")
	public void clientCertificateLogin(String caClientCertificateId, String contextPath, HttpServletRequest request, 
			HttpServletResponse response) {
		Map<String, Object> results = new HashMap<>();
		Map<String, Object> params = new HashMap<>();
		
		try {
			//获取应用的appid
			Map<String, Object> medicalMainstayPathMap = medicalMainstayPathService.findMedicalMainstayByContextPath(contextPath);
			if(null == medicalMainstayPathMap) {
				results.put("isSuccess", false);
				results.put("message", "项目路径配置错误!");
				ResponseUtil.write(response, results);
				return;
			}
			
			params.put("medicalMainstayId", medicalMainstayPathMap.get("medical_mainstay_id"));
			params.put("caClientCertificateId", caClientCertificateId);
			
			Map<String, Object> userMap = usersService.findUserHospitalByCaClientCertificateId(params);
			
			if (userMap != null) {
				results.put("usreName", userMap.get("login_name")!=null?(String)userMap.get("login_name"):null);
				results.put("password", userMap.get("password")!=null?(String)userMap.get("password"):null);
				results.put("medicalMainstayId", userMap.get("medical_mainstay_id")!=null?(String)userMap.get("medical_mainstay_id"):null);
				results.put("id", userMap.get("id")!=null?(String)userMap.get("id"):null);
				results.put("name", userMap.get("name")!=null?(String)userMap.get("name"):"");
				results.put("officeCode", userMap.get("office_code")!=null?(String)userMap.get("office_code"):"");
				results.put("officeName", userMap.get("office_name")!=null?(String)userMap.get("office_name"):"");
				results.put("caClientCertificateId", userMap.get("ca_client_certificate_id")!=null?(String)userMap.get("ca_client_certificate_id"):"");
				results.put("isSuccess", true);
				results.put("message", "登录成功!");
				ResponseUtil.write(response, JSONObject.toJSON(results));
				return;
			}
			
			results.put("isSuccess", false);
			results.put("message", "客户端证书验证失败!");
			ResponseUtil.write(response, JSONObject.toJSON(results));
		} catch (Exception e) {
			e.printStackTrace();
			
			try {
				results.put("isSuccess", false);
				results.put("message", ExceptionUtil.getStackTrace(e));
				ResponseUtil.write(response, JSONObject.toJSON(results));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		
		
	}
	
	/**
	 * 
	 * 新系统
	 * sso 通用用户登录接口-->用户名和密码查询
	 * @param username
	 * @param orgCode
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/userLogin")
	public void login(String username, String password, String contextPath, HttpServletRequest request, 
			HttpServletResponse response) {
		log.info("-------------进入sso:userLogin方法start-----------------");
		Map<String, Object> results = new HashMap<>();
		Map<String, Object> params = new HashMap<>();
		try {
			//获取应用的appid
			Map<String, Object> medicalMainstayPathMap = medicalMainstayPathService.findMedicalMainstayByContextPath(contextPath);
			log.info("-------------进入sso:userLogin方法start"+medicalMainstayPathMap+"-----------------");
			if(null == medicalMainstayPathMap) {
				results.put("isSuccess", false);
				results.put("message", "项目路径配置错误!");
				ResponseUtil.write(response, results);
				return;
				//return new Result(false, "项目路径配置错误!");
			}
			
			params.put("loginName", username);
			params.put("password", password);
			params.put("medicalMainstayId", medicalMainstayPathMap.get("medical_mainstay_id"));
			//查询马甲用户的信息
			Map<String, Object> userMap = usersService.findUserHospitalByLoginNameAndPassword(params);
			
			if(null != userMap) {
				results.put("usreName", username);
				results.put("password", password);
				results.put("medicalMainstayId", userMap.get("medical_mainstay_id")!=null?(String)userMap.get("medical_mainstay_id"):null);
				results.put("id", userMap.get("id")!=null?(String)userMap.get("id"):null);
				results.put("name", userMap.get("name")!=null?(String)userMap.get("name"):"");
				results.put("officeCode", userMap.get("office_code")!=null?(String)userMap.get("office_code"):"");
				results.put("officeName", userMap.get("office_name")!=null?(String)userMap.get("office_name"):"");
				results.put("caClientCertificateId", userMap.get("ca_client_certificate_id")!=null?(String)userMap.get("ca_client_certificate_id"):"");
				results.put("isSuccess", true);
				
				results.put("message", "登录成功!");
				ResponseUtil.write(response, JSONObject.toJSON(results));
				return;
			}else {
				//从用户里面登录
				Users user = usersService.findUserByLoginNameAndPassword(params);
				if(null != user) {
					user.setIsRealUser(2);
					results.put("isSuccess", "true");
					results.put("message", "登录成功!");
					ResponseUtil.write(response, new Result(true, "登录成功!"));
					return;
				}
			}		
			results.put("isSuccess", false);
			results.put("message", "用户名和密码错误!");
			ResponseUtil.write(response, JSONObject.toJSON(results));
		} catch (Exception e) {
			e.printStackTrace();
			try {
				results.put("isSuccess", false);
				results.put("message", ExceptionUtil.getStackTrace(e));
				ResponseUtil.write(response, JSONObject.toJSON(results));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 
	 * 新系统
	 * sso 通用用户登录接口-->通过用户名查询
	 * @param username
	 * @param orgCode
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/loginByUserName")
	public void loginByUserName(String username, String contextPath, HttpServletRequest request, 
			HttpServletResponse response) {
		Map<String, Object> results = new HashMap<>();
		Map<String, Object> params = new HashMap<>();
		try {
			//获取应用的appid
			Map<String, Object> medicalMainstayPathMap = medicalMainstayPathService.findMedicalMainstayByContextPath(contextPath);
			if(null == medicalMainstayPathMap) {
				results.put("isSuccess", false);
				results.put("message", "项目路径配置错误!");
				ResponseUtil.write(response, results);
				return;
				//return new Result(false, "项目路径配置错误!");
			}
			
			params.put("loginName", username);
			params.put("medicalMainstayId", medicalMainstayPathMap.get("medical_mainstay_id"));
			//查询用户的信息
			Map<String, Object> userMap = usersService.findUserHospitalByLoginName(params);
			
			if(null != userMap) {
				results.put("usreName", username);
				results.put("password", (String)userMap.get("password"));
				results.put("medicalMainstayId", userMap.get("medical_mainstay_id")!=null?(String)userMap.get("medical_mainstay_id"):null);
				results.put("id", userMap.get("id")!=null?(String)userMap.get("id"):null);
				results.put("name", userMap.get("name")!=null?(String)userMap.get("name"):"");
				results.put("officeCode", userMap.get("office_code")!=null?(String)userMap.get("office_code"):"");
				results.put("officeName", userMap.get("office_name")!=null?(String)userMap.get("office_name"):"");
				results.put("caClientCertificateId", userMap.get("ca_client_certificate_id")!=null?(String)userMap.get("ca_client_certificate_id"):"");
				results.put("isSuccess", true);
				results.put("message", "登录成功!");
				ResponseUtil.write(response, JSONObject.toJSON(results));
				return;
			}		
			results.put("isSuccess", false);
			results.put("message", "用户名和密码错误!");
			ResponseUtil.write(response, JSONObject.toJSON(results));
		} catch (Exception e) {
			e.printStackTrace();
			try {
				results.put("isSuccess", false);
				results.put("message", ExceptionUtil.getStackTrace(e));
				ResponseUtil.write(response, JSONObject.toJSON(results));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		
	}
	
	
	
	
	/**
	 * 旧系统
	 * 用户登录
	 * @param username
	 * @param orgCode
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody
	public  Result userLogin(String username, String orgCode ,HttpServletRequest request, 
			HttpServletResponse response) {
		try {
			Map<String, Object> results = new HashMap<>();
			Map<String, Object> params = new HashMap<>();
			params.put("orgCode", orgCode);
			params.put("username", username);
			
			TCzy tCzy = userService.findOperationByCardidAndOrgCode(params);
			
			if(null != tCzy) {
				String hexStr = Encrypt.SHA512(new String(username) + UUID.randomUUID().toString());
				String hashStr = new BigInteger(hexStr, 16).toString(36);
				StringBuffer sb = new StringBuffer();
				sb.append(hashStr);
				
				//倒序
				sb.reverse();
				hashStr = sb.toString();
				hashStr = username+"_"+tCzy.getPassword()+"_"+hashStr;
				
				//设置cookie的值 30分钟后过期
				CookieUtils.setCookie(request, response, "TT_TOKEN"+orgCode, hashStr, 1800);
				Constant.USER_NAME=tCzy.getName();
				//CookieUtils.setCookie(request, response, "TT_USERNAME", tCzy.getName(), 1800);
				results.put("usreName", tCzy.getName());
				results.put("password", tCzy.getPassword());
				results.put("orgCode", tCzy.getYyidentiry());
				results.put("cardid", tCzy.getCardid());
				//设置令牌的值
				results.put("TT_TOKEN", hashStr);
				
				return new Result(true, "登录成功!", results);
			} else {
				return new Result(false, "用户名和密码错误!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, ExceptionUtil.getStackTrace(e), "500");
		}
		
	}
	
	@GetMapping("/error")
	public String error(){
		return "error/error";
	}
	
	
	
	
	/**
	 * 旧系统的权限
	 * 
	 * @param username
	 * @param password
	 * @param orgCode
	 * @param request
	 * @return
	 */
	@PostMapping("/findOperationAuthorityList")
	@ResponseBody
	public Result findOperationAuthorityList(String username, String password, String orgCode, HttpServletRequest request) {
		try {
			Map<String, Object> params = new HashMap<>();
			
			params.put("username", username);
			params.put("password", password);
			params.put("orgCode", orgCode);
			
			List<Authority> authorityList = userService.findOperationAuthorityList(params);
			
			return new Result(true, "查询成功!", authorityList);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, ExceptionUtil.getStackTrace(e), "500");
		}
		
	}
	
	/**
	 * 新系统的权限
	 * 
	 * @param username
	 * @param password
	 * @param orgCode
	 * @param request
	 * @return
	 */
	@PostMapping("/findAuthorityList")
	@ResponseBody
	public Result findAuthorityList(String userId, String medicalMainstayId, HttpServletRequest request) {
		try {
			Map<String, Object> params = new HashMap<>();
			Set<String> ahthoritySet = authorityService.findAuthorityListByRoleId(userId, medicalMainstayId);
	/*		
			Map<String,Object> ahthorityList= authorityService.findAuthorityListByRoleId(userId, medicalMainstayId);
			*/
			return new Result(true, "查询成功!", ahthoritySet);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, ExceptionUtil.getStackTrace(e), "500");
		}
		
	}
	
	
}

